package com.itcast.plane.modoule.flight.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.plane.common.ConsHint;
import com.itcast.plane.modoule.company.domain.Company;
import com.itcast.plane.modoule.flight.domain.Flight;
import com.itcast.plane.modoule.flight.dto.*;
import com.itcast.plane.modoule.flight.mapper.FlightMapper;
import com.itcast.plane.modoule.indent.domain.Indent;
import com.itcast.plane.modoule.indent.mapper.IndentMapper;
import com.itcast.plane.modoule.path.domain.Path;
import com.itcast.plane.modoule.planes.domain.Planes;
import com.itcast.plane.modoule.ticket.domain.Ticket;
import com.itcast.plane.modoule.ticket.dto.TicketCreatDTO;
import com.itcast.plane.modoule.ticket.service.TicketService;
import com.itcast.plane.util.CommonService;
import com.itcast.plane.util.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FlightService extends ServiceImpl<FlightMapper, Flight> {

    @Resource
    private FlightMapper flightMapper;

    @Resource
    private TicketService ticketService;

    @Resource
    private CommonService commonService;

    @Resource
    private IndentMapper indentMapper;

    public JsonResult addFlight(FlightCreatDTO creatDTO) {
        //条件判断
        Planes planes = commonService.getPlanesById(creatDTO.getPlaneId());
        if (ObjectUtils.isEmpty(planes)) {
            return new JsonResult(false, "添加失败!飞机型号不存在");
        }
        if (ObjectUtils.isEmpty(commonService.getCompanyById(creatDTO.getCompId()))) {
            return new JsonResult(false, "添加失败!航空公司不存在");
        }
        if (ObjectUtils.isEmpty(commonService.getPathById(creatDTO.getPathId()))) {
            return new JsonResult(false, "添加失败!所选线路不存在");
        }
        //新建票务
        TicketCreatDTO ticketCreatDTO = new TicketCreatDTO();
        ticketCreatDTO.setFirstPrice(creatDTO.getFirstPrice());
        ticketCreatDTO.setSecondPrice(creatDTO.getSecondPrice());
        ticketCreatDTO.setThirdPrice(creatDTO.getThirdPrice());
        ticketCreatDTO.setOilPrice(creatDTO.getOilPrice());
        ticketCreatDTO.setFirstNum(planes.getFirstNum());
        ticketCreatDTO.setSecondNum(planes.getSecondNum());
        ticketCreatDTO.setThirdNum(planes.getThirdNum());
        int ticketId = ticketService.addTicket(ticketCreatDTO);
        //新建航班
        Flight flight = new Flight();
        BeanUtils.copyProperties(creatDTO, flight);
        flight.setTicketId(ticketId);
        flightMapper.insert(flight);
        return new JsonResult(true, ConsHint.INSERT_SUCCESS);
    }

    public JsonResult deleteFlight(int id) {
        if (getFlag(id)) {
            flightMapper.deleteById(id);
            return new JsonResult(true, ConsHint.DELETE_SUCCESS);
        } else {
            return new JsonResult(false, ConsHint.DELETE_DEFAULT_USING);
        }
    }

    public JsonResult editFlight(FlightEditDTO flightEditDTO) {
        if (getFlag(flightEditDTO.getId())) {
            //票价修改
            Ticket ticket = new Ticket();
            BeanUtils.copyProperties(flightEditDTO, ticket);
            ticket.setId(flightEditDTO.getTicketId());
            ticketService.editTicket(ticket);
            //航班其他信息修改
            Flight flight = new Flight();
            BeanUtils.copyProperties(flightEditDTO, flight);
            flightMapper.updateById(flight);
            return new JsonResult(true, ConsHint.EDIT_SUCCESS);
        } else {
            return new JsonResult(false, ConsHint.EDIT_DEFAULT_USING);
        }
    }

    //管理员用列表
    public JsonResult getFlight(int pages) {
        LambdaQueryWrapper<Flight> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Flight> flights = flightMapper.selectList(lambdaQueryWrapper.eq(Flight::getIfDelete, 0).orderByAsc(Flight::getId));
        //分页
        List<Flight> returnList = new ArrayList<>();
        for (int i = 10 * (pages - 1); i < pages * 10; i++) {
            if (i < flights.size()) {
                returnList.add(flights.get(i));
            }
        }
        List<FlightPageVO> list = new ArrayList<>();
        for (Flight flight : returnList) {
            FlightPageVO flightVO = new FlightPageVO();
            Planes planes = commonService.getPlanesById(flight.getPlaneId());
            Company company = commonService.getCompanyById(flight.getCompId());
            Path path = commonService.getPathById(flight.getPathId());
            Ticket ticket = commonService.getTicketById(flight.getTicketId());
            flightVO.setCompName(company.getName());
            flightVO.setDeparture(path.getDeparture());
            flightVO.setDestination(path.getDestination());
            flightVO.setPlaneName(planes.getName());
            BeanUtils.copyProperties(ticket, flightVO);
            BeanUtils.copyProperties(flight, flightVO);
            list.add(flightVO);
        }
        return new JsonResult(true,String.valueOf(flights.size()), list);
    }

    //修改、删除条件查询，卖出票则不允许修改
    private boolean getFlag(int id) {
        LambdaQueryWrapper<Indent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Indent indent = indentMapper.selectOne(lambdaQueryWrapper.eq(Indent::getFlightId, id));
        return ObjectUtils.isEmpty(indent);
    }

    //用户查询
    public JsonResult getAppPage(FlightAppDTO appDTO) {
        LambdaQueryWrapper<Flight> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(appDTO.getDeparture()) && StringUtils.isNotBlank(appDTO.getDestination())) {
            LambdaQueryWrapper<Path> pathLambdaQueryWrapper = new LambdaQueryWrapper<>();
            List<Path> paths = commonService.getPathByLambda(pathLambdaQueryWrapper.eq(Path::getDeparture, appDTO.getDeparture())
                    .eq(Path::getDestination, appDTO.getDestination()));
            List<Integer> ids = new ArrayList<>();
            for (Path path : paths) {
                ids.add(path.getId());
            }
            if (ids.size() == 0){
                return new JsonResult(false,"没有该航线的信息");
            }
            if (ids.size()>1) {
                lambdaQueryWrapper.in(Flight::getPathId, ids);
            }else {
                lambdaQueryWrapper.eq(Flight::getPathId,ids.get(0));
            }
        }
        if (StringUtils.isNotBlank(String.valueOf(appDTO.getDepartureTime()))) {
            Date date = new Date();
            long time = date.getTime();
            lambdaQueryWrapper.ge(Flight::getDepartureTime, Math.max(time, appDTO.getDepartureTime()));
        }
        lambdaQueryWrapper.eq(Flight::getIsCheep, appDTO.getIsCheep()).eq(Flight::getIfFly,0)
                .orderByDesc(Flight::getId);
        List<Flight> flights = flightMapper.selectList(lambdaQueryWrapper);
        List<FlightAppVO> list = new ArrayList<>();
        for (Flight flight : flights) {
            FlightAppVO vo = new FlightAppVO();
            Path path = commonService.getPathById(flight.getPathId());
            BeanUtils.copyProperties(path,vo);
            Planes planes = commonService.getPlanesById(flight.getPlaneId());
            vo.setPlaneName(planes.getName());
            Ticket ticket = commonService.getTicketById(flight.getTicketId());
            BeanUtils.copyProperties(ticket,vo);
            Company company = commonService.getCompanyById(flight.getCompId());
            vo.setCompName(company.getName());
            BeanUtils.copyProperties(flight,vo);
            list.add(vo);
        }
        return new JsonResult(true,list);
    }
}
